<?php
// 应用公共文件
declare(strict_types=1);

use app\common\exception\TipsException;
use app\common\enum\RespCode;
use think\Response;

//获取IP
function getIp() {
	$realip = '';
	if (isset($_SERVER)) {
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
			$realip = $_SERVER['HTTP_CLIENT_IP'];
		} else {
			$realip = $_SERVER['REMOTE_ADDR'];
		}
	} else {
		if (getenv("HTTP_X_FORWARDED_FOR")) {
			$realip = getenv( "HTTP_X_FORWARDED_FOR");
		} elseif (getenv("HTTP_CLIENT_IP")) {
			$realip = getenv("HTTP_CLIENT_IP");
		} else {
			$realip = getenv("REMOTE_ADDR");
		}
	}
	return $realip;
}
function rands($len)
{
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    $string = substr((string) time(), -3);
    for (; $len >= 1; $len--) {
        $position = rand() % strlen($chars);
        $position2 = rand() % strlen($string);
        $string = substr_replace($string, substr($chars, $position, 1), $position2, 0);
    }
    return $string;
}
    /**
     * 多级线性结构排序
     * 转换前：
     * [{"id":1,"pid":0,"name":"a"},{"id":2,"pid":0,"name":"b"},{"id":3,"pid":1,"name":"c"},
     * {"id":4,"pid":2,"name":"d"},{"id":5,"pid":4,"name":"e"},{"id":6,"pid":5,"name":"f"},
     * {"id":7,"pid":3,"name":"g"}]
     * 转换后：
     * [{"id":1,"pid":0,"name":"a","level":1},{"id":3,"pid":1,"name":"c","level":2},{"id":7,"pid":3,"name":"g","level":3},
     * {"id":2,"pid":0,"name":"b","level":1},{"id":4,"pid":2,"name":"d","level":2},{"id":5,"pid":4,"name":"e","level":3},
     * {"id":6,"pid":5,"name":"f","level":4}]
     * @param array $data 线性结构数组
     * @param string $symbol 名称前面加符号
     * @param string $name 名称
     * @param string $id_name 数组id名
     * @param string $parent_id_name 数组祖先id名
     * @param int $level 此值请勿给参数
     * @param int $parent_id 此值请勿给参数
     * @return array
     */
    function linear_to_tree($data, $sub_key_name = 'sub', $id_name = 'id', $parent_id_name = 'pid', $parent_id = 0)
    {
        $tree = [];
        foreach ($data as $row) {
            if ($row[$parent_id_name] == $parent_id) {
                $temp = $row;
                $child = linear_to_tree($data, $sub_key_name, $id_name, $parent_id_name, $row[$id_name]);
                if ($child) {
                    $temp[$sub_key_name] = $child;
                }else{
                    $temp[$sub_key_name] = [];
                }
                $tree[] = $temp;
            }
        }
        return $tree;
    }
if (!function_exists('make')) {
    /**
     * 实例化类
     * @param string $name
     * @param ...$parameter
     */
    function make(string $name, ...$parameter): object
    {
        return new $name(...$parameter);
    }
}
if (!function_exists('recursion')) {
    /**
     * 递归遍历
     * @param array $data 遍历的数组
     * @param int $index 顶级id
     * @param bool $child true没有子集不显示父级
     * @param string $pk tree键名
     * @param string $ck list键名
     */
    function recursion(array $data, $index = 0, $children = false, $pk = 'pid', $ck = 'id'): array
    {
        $result = [];
        foreach ($data as $item) {
            if ($index == $item[$pk]) {
                $subset = recursion($data, $item[$ck], $children, $pk, $ck);
                if ($children) {
                    if ($subset) {
                        $item['children'] = $subset;
                        $result[] = $item;
                    }
                } else {
                    $item['children'] = $subset;
                    $result[] = $item;
                }
            }
        }
        return $result;
    }
}




if (!function_exists('resp_header')) {
    /**
     * 响应报文
     * @param Response|null $response
     * @param array $data
     * @param string $type
     * @param integer $code
     * @param array $header
     * @param array $options
     */

    function resp_header(Response $response = null, $data = [], $type = 'json', $code = 200, $header = [], $options = []): Response
    {
        if ($response == null) {
            $response = Response::create($data, $type, $code);
        }
        if (!$header) {
            $header = [
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Methods' => 'POST,GET,PUT,DELETE,OPTIONS',
                'Access-Control-Allow-Headers' => 'X-Requested-With,Content-Type,Token,Authorization,X-Token',
                'Content-Type' => 'application/json; charset=utf-8',
                'Access-Control-Allow-Credentials' => 'false',
                'Access-Control-Max-Age' => 1800
            ];
        }
        return $response->header($header)->options($options);
    }
    if (!function_exists('tips'))
    {
        /**
         * 客户端错误提示
         * @param string $message
         * @param integer $code
         */
        function tips(string $message, $code = RespCode::ERROR): void
        {
            throw new TipsException($message, $code);
        }
    }

    if (!function_exists('list_fmt')) {
        /**
         * 列表数据格式
         * @param array|object $rows 列表数据
         * @param int $total 总数
         * @param string|array $other 其他
         */
        function list_fmt($rows, $total = 0, $other = '',$param=[]): array
        {
            //$param = request()->param();
            if(!$param){
                $param['page'] =1;
                $param['pageSize']=10;
            }

            return [
                'rows' => $rows,
                'total' =>(int) $total,
                'page' =>(int) $param['page'],
                'pageSize' =>(int) $param['pageSize'],
                'other' => $other
            ];
        }
    }
    if (!function_exists('is_mkdir')) {
        /**
         * 创建目录
         * @param string $dir
         */
        function is_mkdir(string $dir): bool
        {
            if (is_dir($dir) || mkdir($dir, 0777, true)) {
                return true;
            }
            tips('创建目录失败');
        }
    }

    if (!function_exists('unique_tag')) {
        /**
         * 唯一标识获取
         */
        function unique_tag(): string
        {
            return md5(uniqid() . microtime(true));
        }
    }
}